package com.mac.web;

import com.alibaba.fastjson.JSON;
import com.mac.pojo.ArticleView;
import com.mac.pojo.Articles;
import com.mac.pojo.Member;
import com.mac.service.ArticlesService;
import com.mac.service.MemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;

/**
 *  定义ArticleServlet类，用于处理与文章相关的请求
 */
@WebServlet("/articles/*")
public class ArticleServlet extends BaseServlet {

    // 使用SLF4J记录日志
    private static final Logger LOGGER = LoggerFactory.getLogger("ArticleServlet.Class");

    // 注入文章服务类，用于与文章数据交互
    ArticlesService articlesService = new ArticlesService();
    // 注入会员服务类，用于与会员数据交互
    MemberService memberService = new MemberService();

    /**
     * 获取所有文章的方法。
     * @param request 请求对象，包含请求信息。
     * @param response 响应对象，用于返回响应数据。
     * @throws ServletException 如果发生Servlet异常。
     * @throws IOException 如果发生I/O异常。
     */
    public void selectAllArticles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 初始化文章列表，用于存储所有文章数据
        ArrayList<Articles> articles;
        try {
            // 调用文章服务方法，获取所有文章
            articles = articlesService.selectAllArticles();
            LOGGER.info("articlesService.selectAllArticles() -> succeed");
        } catch (Exception e) {
            // 记录错误并抛出运行时异常
            LOGGER.error("articlesService.selectAllArticles() -> failed",e);
            throw new RuntimeException(e);
        }

        // 初始化文章视图列表，用于存储转换后的文章视图数据
        ArrayList<ArticleView> articleViews = new ArrayList<>();

        // 遍历文章列表，转换为文章视图
        for (Articles article : articles) {
            ArticleView articleView = new ArticleView();

            // 获取文章作者信息
            Member member;
            try {
                member = memberService.selectByUserId(article.getAuthorId());
                LOGGER.info("memberService.selectByUserId(article.getAuthorId()) -> succeed");
            } catch (Exception e) {
                // 记录错误并抛出运行时异常
                LOGGER.error("memberService.selectByUserId(article.getAuthorId()) -> failed",e);
                throw new RuntimeException(e);
            }

            // 设置文章视图的属性
            articleView.setArticleId(article.getArticleId());
            articleView.setTitle(article.getTitle());
            articleView.setContent(article.getContent());
            articleView.setPublishDate(new Timestamp(article.getPublishDate().getTime())); // 确保传入的是 Timestamp
            articleView.setAuthor(member.getMemberName());

            // 将文章视图添加到列表中
            articleViews.add(articleView);
        }

        // 将文章视图列表转换为JSON格式
        String jsonString = JSON.toJSONString(articleViews);

        // 设置响应内容类型并写入JSON字符串
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    /**
     * 根据文章标题获取文章的方法。
     * @param request 请求对象，包含请求信息。
     * @param response 响应对象，用于返回响应数据。
     * @throws ServletException 如果发生Servlet异常。
     * @throws IOException 如果发生I/O异常。
     */
    public void selectByArticleTitle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从请求参数中获取文章ID
        String article_Id = request.getParameter("articleId");

        // 将文章ID转换为整数
        int articleId = Integer.parseInt(article_Id);

        // 初始化文章对象，用于存储查询结果
        Articles article;
        try {
            // 调用文章服务方法，根据ID查询文章
            article = articlesService.searchOneByArticleId(articleId);
            LOGGER.info("articlesService.searchOneByArticleId(articleId) -> succeed");
        } catch (Exception e) {
            // 记录错误并抛出运行时异常
            LOGGER.error("articlesService.searchOneByArticleId(articleId) -> failed",e);
            throw new RuntimeException(e);
        }

        // 初始化文章视图对象，用于存储转换后的文章视图数据
        ArticleView articleView = new ArticleView();

        // 获取文章作者信息
        Member member;
        try {
            member = memberService.selectByUserId(article.getAuthorId());
            LOGGER.info("memberService.selectByUserId(article.getAuthorId()) -> succeed");
        } catch (Exception e) {
            // 记录错误并抛出运行时异常
            LOGGER.error("memberService.selectByUserId(article.getAuthorId()) -> failed",e);
            throw new RuntimeException(e);
        }

        // 设置文章视图的属性
        articleView.setTitle(article.getTitle());
        articleView.setContent(article.getContent());
        articleView.setPublishDate(new Timestamp(article.getPublishDate().getTime())); // 确保传入的是 Timestamp
        articleView.setAuthor(member.getMemberName());

        // 将文章视图转换为JSON格式
        String jsonString = JSON.toJSONString(articleView);

        // 设置响应内容类型并写入JSON字符串
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
}